package com.lyl.myaiagent.agent;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lyl
 * @version 1.0
 * @CreateTime: 2025-08-20
 */
@Slf4j
@Data
public abstract class BaseAgent {

    // 智能体名称
    private String name;

    // 提示词
    private String SystemPrompt;
    private String nextStepPrompt;

    // 状态
    AgentState state = AgentState.IDLE;

    // 大模型
    private ChatClient client;

    // 执行步骤
    int currentStep = 0;
    int maxSteps = 10;

    // 记忆Memory
    private List<Message> messageList = new ArrayList<>();


    public String run(String userPrompt){
        if(this.state != AgentState.IDLE){
            throw new RuntimeException("Cannot run agent from state:"+ this.state);
        }
        if(StrUtil.isBlank(userPrompt)){
            throw new RuntimeException("Cannot run agent with empty user prompt");
        }
        // 更新为运行状态
        state = AgentState.RUNNING;

        // 记录消息上下文
        messageList.add(new UserMessage(userPrompt));

        // 记录工具调用结果
        List<String> toolResults = new ArrayList<>();

        try {
            for(int i = 0; i < maxSteps && state != AgentState.FINISHED; i++){
                int stepNumber = i + 1;
                currentStep = stepNumber;
                log.info("正在执行，当前步骤：" + currentStep + "/" + maxSteps);

                // 单步执行
                String stepResult = step();
                String result = "步骤[" + currentStep + "] :" + stepResult;
                toolResults.add(result);
            }

            // 检查工具是否达到最大步骤
            if(currentStep >= maxSteps){
                state = AgentState.FINISHED;
                toolResults.add("终止循环：已经达到预设最大步骤：" + maxSteps);
            }

            return String.join("\n", toolResults);
        } catch (Exception e) {
            state = AgentState.ERROR;
            log.error("模型执行错误：", e);
            return "模型执行错误" + e.getMessage();
        }finally {
            clean();
        }
    }

    /**
     * 执行单个步骤
     * @return 步骤执行的结果
     */
    public abstract String step();

    /**
     * 清理资源
     */
    protected  void clean(){

    }
}
